@page "/QuickCreateTicket"
@using System.ComponentModel.DataAnnotations
@using WorkOrder.Interfaces
@using WorkOrder.Models
@using BootstrapBlazor.Components
@using WorkSystem.Data
@attribute [UserNavigation("快捷建单")]
@attribute [TabItemOption(Text = "快捷建单", Icon = "fa-solid fa-file-circle-plus")]
@rendermode InteractiveServer
<PageTitle>快捷建单</PageTitle>
 
    <div class="container mt-4">
          <ValidateForm Model="newTicketView" OnValidSubmit="SubmitWorkOrder" >
        <div class="row mb-4">
            <div class="col-md-12">
                <h3 class="text-primary">快捷建单</h3>
                <p class="text-muted">将模板字段内容粘贴到下方文本框中，系统会自动解析并生成工单。</p>
            </div>
        </div>
          <div class="row mb-4"> 
            <div class="col-md-12">
                <Select @bind-Value="newTicketView.优先级" Items="@(Enum.GetValues<PriorityLevel>().Select(p => new SelectedItem(p.ToString(), p.ToString())).ToList())">

                    <ItemTemplate>
              
                    <Badge IsPill="true" Color="@GetPriorityColor(Enum.Parse<PriorityLevel>(context.Text))">@context.Text</Badge>

                    </ItemTemplate>
                </Select>
                <BootstrapInput PlaceHolder="请输入 ..."
                        TValue="string"
                        IsAutoFocus="true"
                         @bind-Value="newTicketView.工单标题"
                        IsSelectAllTextOnFocus="true"
                        ShowLabel="true"
                        DisplayText="工单标题" />
               <Select @bind-Value="newTicketView.流程ID" ShowSearch="true" Items="@ProcessList" PlaceHolder="请选择流程模板">
                    <ItemTemplate>
                        @if (string.IsNullOrEmpty(context.Value))
                        {
                            <div class="mt-3 text-danger">请选择一个流程模板</div>
                        }
                        else
                        {
                            <div class="mt-3 text-success">已选择流程模板: @context.Text</div>
                        }
                    </ItemTemplate>
                </Select>
            </div>
        </div>
        <div class="row mb-4">
            <div class="col-md-12">
                <Textarea @bind-Value="newTicketView.工单内容"  Rows="10" Placeholder="请输入表单内容" />
                <Button Class="mt-3" Color="Color.Primary" OnClick="ParseTemplateContent">
                    <i class="fa-solid fa-file-circle-plus me-2"></i>解析并生成工单
                </Button>
            </div>
        </div>

        @if (SelectedTemplate != null)
        {
            <div class="alert alert-info">
                已匹配模板：<strong>@SelectedTemplate.模板名称</strong>
            </div>

        @if (newTicketView.扩展字段.Any())
        {
            <div class="row mt-4">
                <div class="col-md-12">
                    <h4 class="text-success">解析结果</h4>
                    <ul>
                        @foreach (var field in newTicketView.扩展字段)
                        {
                            
                                <li><strong>@field.Key:</strong> @field.Value</li>
                            
                        }
                     </ul>
                       <Button Color="Color.Primary" Icon="fa-solid fa-check me-2" ButtonType="ButtonType.Submit">提交工单</Button>
 
                </div>
            </div>
        }
        }

       </ValidateForm>
    </div>
 

@code {

    private  NewTicketView newTicketView = new NewTicketView();
 
 

    private List<SelectedItem> ProcessList { get; set; } = new();
    private 工单模板表? SelectedTemplate { get; set; }

    [Inject]
    private IWorkOrderService WorkOrderService { get; set; }

    [Inject]
    private ToastService ToastService { get; set; }

 
    [Inject]
    private MyIdentityContext AppContext { get; set; }
    [Inject]
    [NotNull]
    private ISystemNotificationService SystemNotificationService { get; set; }
  protected override async Task OnInitializedAsync()
    {
          ProcessList = (await WorkOrderService.GetProcessList())
            .Select(p => new SelectedItem { Value = p.流程ID!, Text = p.流程名称 })
            .ToList();

        
    }
    private Color GetPriorityColor(PriorityLevel priority) => priority switch
{
    PriorityLevel.低 => Color.Secondary,
    PriorityLevel.正常 => Color.Success,
    PriorityLevel.高 => Color.Warning,
    PriorityLevel.紧急 => Color.Danger,
    _ => Color.Light
};
private async Task ParseTemplateContent()
{
    try
    {

        
        SelectedTemplate=null;
   
        newTicketView.扩展字段.Clear();
        newTicketView.ConvertContentToExtendedFields();
       
        if (!newTicketView.扩展字段.Any())
        {
                await ToastService.Warning("解析失败", "未能解析任何字段，请检查粘贴内容的格式");
                return;
        }
        var matchedTemplate = await IdentifyTemplate(newTicketView.扩展字段.Keys);
        if (matchedTemplate == null)
        {
            await ToastService.Warning("解析失败", "无法识别模板，请检查字段内容是否完整");
            return;
        }

        SelectedTemplate = matchedTemplate;
        await ToastService.Success("解析成功", $"已匹配模板：{SelectedTemplate.模板名称}");
        StateHasChanged();

    }
    catch (Exception ex)
    {
        await ToastService.Error("解析失败", ex.Message);
      
    }
}
    private async Task<工单模板表?> IdentifyTemplate(IEnumerable<string> fieldDisplayNames)
    {
        // 获取所有模板及其字段
        var templates = await WorkOrderService.GetTemplateList();

        foreach (var template in templates)
        {
            // 获取模板的所有字段显示名称
            var templateDisplayNames = template.字段定义.Select(f => f.字段名称).ToHashSet(StringComparer.OrdinalIgnoreCase);

            // 获取模板的必填字段
            var requiredFields = template.字段定义
                .Where(f => f.是否必填)
                .Select(f => f.字段名称)
                .ToHashSet(StringComparer.OrdinalIgnoreCase);

            

            // 检查是否包含所有必填字段
            bool containsAllRequiredFields = requiredFields.All(f => fieldDisplayNames.Contains(f.Trim(), StringComparer.OrdinalIgnoreCase));

            // 如果包含所有必填字段，则返回该模板
            if (containsAllRequiredFields)
            {
                return template;
            }
        }

        // 如果没有匹配到任何模板，则返回 null
        return null;
    }

    

      private async Task SubmitWorkOrder(EditContext editContext)
    {
        try
        {   
     
            var workOrderData = new Dictionary<string, object>(newTicketView.扩展字段);
            
            // 调用服务保存工单
           
            var result = await WorkOrderService.CreateWorkOrderAsync(new 工单主表
            {
                工单标题 = newTicketView.工单标题,
                问题描述 = SelectedTemplate.模板名称,
                扩展字段 = newTicketView.扩展字段, 
                模板ID = SelectedTemplate.模板ID,
                创建人id = AppContext.UserName,
                优先级 = newTicketView.优先级,
                截止时间 = newTicketView.优先级 switch
                {
                    PriorityLevel.低 => DateTime.Now.AddMinutes(50),
                    PriorityLevel.正常 => DateTime.Now.AddMinutes(30),
                    PriorityLevel.高 => DateTime.Now.AddMinutes(15),
                    PriorityLevel.紧急 => DateTime.Now.AddMinutes(10),
                    _ => DateTime.Now.AddMinutes(30) // 默认值
                },
                总金额= workOrderData.ContainsKey("金额") ? Convert.ToDecimal(workOrderData["金额"]) : 0,
                创建时间 = DateTime.Now,
            },newTicketView.流程ID);
            await  WorkOrderService.TransitionToNextNodeAsync(result.工单id, AppContext.UserName);
            if (result!=null)
            {
                await ToastService.Success("提交成功", "工单已成功创建");
                newTicketView=new NewTicketView();
                SelectedTemplate = null;
                var permissionInfo = await WorkOrderService.GetProcessInstanceByWorkOrderIdAsync(result.工单id);

                if (permissionInfo?.当前节点 != null)
                {
                    switch (permissionInfo.当前节点.负责人规则类型)
                    {
                        case AssignRuleType.角色:
                            if (!string.IsNullOrEmpty(permissionInfo.当前节点.负责人规则参数))
                            {
                                await SystemNotificationService.SendSystemNotificationAsync(
                                    Constant.RoleMessagge,
                                    DispatchType.Toast,
                                    "您有新的工单等待处理",
                                    $"用户:{AppContext.UserName} 创建了工单等待您审核 1 个工单",
                                    permissionInfo.当前节点.负责人规则参数
                                );
                            }
                            break;

                        case AssignRuleType.指定用户:
                            if (!string.IsNullOrEmpty(permissionInfo.当前节点.负责人规则参数))
                            {
                                await SystemNotificationService.SendSystemNotificationAsync(
                                    Constant.UserMessagge,
                                    DispatchType.Toast,
                                    "您有新的工单等待处理",
                                    $"用户:{AppContext.UserName} 创建了工单等待您审核 1 个工单",
                                    permissionInfo.当前节点.负责人规则参数
                                );
                            }
                            break;
                    }
                }
               
                StateHasChanged();
            }
            else
            {
                await ToastService.Error("提交失败", "工单创建失败，请重试");
            }
        }
        catch (Exception ex)
        {
            await ToastService.Error("提交失败", ex.Message);
        }
    }
}